﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Text;
using UnityEngine.UI;
public class UIMgr : MonoBehaviour {

    string PrefabRoute = "UI/";

    #region 实例化画布
    private GameObject m_ocanvas;
    public GameObject m_oCANVAS
    {
        get
        {
            if (null == m_ocanvas)
            {
                UnityEngine.Object obj = Resources.Load("UI/Canvas");
                m_ocanvas = Instantiate(obj) as GameObject;
                m_ocanvas.name = obj.name;
            }
            return m_ocanvas;
        }
    }
    #endregion

    //加载UI
    public T UI<T>(bool bLoad = true) where T : Component
    {
        Type t = typeof(T);
        StringBuilder sb = new StringBuilder(PrefabRoute);
        sb.Append(t.Name);
        T rel = null;
        if (bLoad)  //实例化相应UI
        {
            UnityEngine.Object obj = Resources.Load(sb.ToString());
            GameObject _obj = Instantiate(obj) as GameObject;
            _obj.name = obj.name;
            _obj.transform.SetParent(m_oCANVAS.transform);
            _obj.transform.localPosition = Vector3.zero;
            _obj.transform.localScale = Vector3.one;
            rel = _obj.GetOrAddComponent<T>();
        }
        else       //找到相应UI
        {
            for (int i = 0; i < m_oCANVAS.transform.childCount; i++)
            {
                if (t.Name == m_oCANVAS.transform.GetChild(i).name)
                {
                    rel = m_oCANVAS.transform.GetChild(i).GetComponent<T>();
                }
            }
        }

        return rel;
    }
}
